/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.storagepool.task;

import com.alibaba.fastjson2.JSON;
import com.dsms.common.constant.RemoteResponseStatusEnum;
import com.dsms.common.constant.TaskStatusEnum;
import com.dsms.common.remotecall.model.FailedDetail;
import com.dsms.common.remotecall.model.FinishedDetail;
import com.dsms.common.remotecall.model.RemoteResponse;
import com.dsms.common.taskmanager.TaskException;
import com.dsms.common.taskmanager.model.Step;
import com.dsms.common.taskmanager.service.IStepService;
import com.dsms.dfsbroker.osd.crushmap.api.CrushmapApi;
import com.dsms.modules.util.RemoteCallUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Component
public class GetCrushmapStepResult {

    private final CrushmapApi crushmapApi;
    private final IStepService stepService;

    @Autowired
    public GetCrushmapStepResult(CrushmapApi crushmapApi, IStepService stepService) {
        this.crushmapApi = crushmapApi;
        this.stepService = stepService;
    }

    /**
     * this function used to get the response of update crushmap, and according response to update the step in database
     *
     * @param step
     * @param executeResponse the response of dsms-broker's asynchronous request
     * @param require         the required string used to determine whether the task was successful
     * @param errMsg          the step error message prefix. example: pool add node failed
     * @return Step
     * @throws Throwable
     */
    public Step getStepResponse(Step step, RemoteResponse executeResponse, String require, String errMsg) throws Throwable {
        //get response of step request
        RemoteResponse resultResponse = crushmapApi.getUpdateCrushmapResult(RemoteCallUtil.generateRemoteRequest(), executeResponse.getId());

        //analytic response result
        if (Objects.equals(resultResponse.getState(), RemoteResponseStatusEnum.SUCCESS.getMessage())) {
            List<FinishedDetail> finished = resultResponse.getFinished();
            String outs = finished.get(0).getOuts();
            String outb = finished.get(0).getOutb();
            String out = StringUtils.hasText(outs) ? outs : outb;
            if (Objects.equals(require, out) || out.startsWith(require)) {
                step.setStepStatus(TaskStatusEnum.FINISH.getStatus());
                step.setStepEndTime(LocalDateTime.now());
            } else {
                step.setStepErrorMessage(out);
                step.setStepEndTime(LocalDateTime.now());
                step.setStepStatus(TaskStatusEnum.FAIL.getStatus());
                stepService.updateById(step);
                throw new TaskException(errMsg + ":" + out);
            }
        } else if (Objects.equals(resultResponse.getState(), RemoteResponseStatusEnum.FAILED.getMessage())) {
            List<FailedDetail> failed = resultResponse.getFailed();
            String outs = failed.get(0).getOuts();
            String outb = failed.get(0).getOutb();
            String out = StringUtils.hasText(outs) ? outs : outb;
            step.setStepErrorMessage(out);
            step.setStepStatus(TaskStatusEnum.FAIL.getStatus());
            step.setStepEndTime(LocalDateTime.now());
            stepService.updateById(step);
            throw new TaskException(errMsg + "," + out);
        } else if (ObjectUtils.isEmpty(resultResponse.getState())) {
            stepService.updateById(step);
            throw new TaskException("unknown request state,response:" + JSON.toJSONString(resultResponse));
        }
        stepService.updateById(step);
        return step;
    }
}
